<?php

namespace App\Http\Controllers\AdminApi;

use App\Services\Config as ConfigService;

use Illuminate\Http\Request;
//use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Exception;

/**
 * 公共的方法
 */
class CommonController extends BaseController
{
    /**
     * 验证码
     */
    public function captcha(Request $request)
    {
        $param['api'] = true;
        $captcha = \App\Services\Verify::entry($param);

        return api_response(config('constants.STATUS_SUCCESS'), '', [
            'key' => $captcha['key'],
            'src' => $captcha['data'],
            'switch' => true, // 是否启用
        ]);
    }

    /**
     * 设置
     */
    public function setting(Request $request)
    {
        $key = 'system_setting';
        if ($request->isMethod('post')) {
            $param = $request->all();
            $value = [
                'favicon_url' => $param['favicon_url'],
                'login_bg_url' => $param['login_bg_url'],
                'login_logo_url' => $param['login_logo_url'],
                'logo_url' => $param['logo_url'],
                'page_title' => $param['page_title'],
                'system_name' => $param['system_name'],
            ];
            $result = ConfigService::setOption($key, $key, $value);
            if ($result === false) {
                return api_response(config('constants.STATUS_ERROR'), '设置失败！', $value);
            }

            return api_response(config('constants.STATUS_SUCCESS'), '成功', []);
        }

        $info = ConfigService::getOption($key, $key);
        if (!$info) {
            $info = [
                'system_name' => '后台管理系统',
                'login_logo_url' => '',
                'login_bg_url' => asset('static/admin/img/login_bg.jpg'),
                'page_title' => 'VueAdmin系统',
                'logo_url' => '',
                'favicon_url' => '',
            ];
        }

        return api_response(config('constants.STATUS_SUCCESS'), '', $info);
    }

    /**
     * 清除缓存
     */
    public function delCache(Request $request)
    {
        // 清除admin标签的缓存数据
        // 使用 file、dynamodb 或 database 缓存驱动程序时不支持缓存标签
        //Cache::tags(['admin'])->flush();
        Cache::flush(); // 登录token缓存也会被删除

        return api_response(config('constants.STATUS_SUCCESS'), '清除缓存成功！', []);
    }

    /**
     * 文件上传
     */
    public function upload(Request $request)
    {
        $respJson = \App\Services\UploaderService::upload($request);
        $result = json_decode($respJson->getContent(), true);
        if ($result['code'] != 1) {
            return api_response(config('constants.STATUS_ERROR'), $result['msg'], '');
        }
        $data = [
            'name' => $result['filename'],
            'src' => $result['full_filepath'],
            'size' => $result['filesize'],
            'date' => date('Y-m-d H:i:s'),
            //'creator_id' => $this->admin['id'],
            'filepath' => $result['filepath'],
            'full_filepath' => $result['full_filepath'],
            //'result' => $result
        ];

        return api_response(config('constants.STATUS_SUCCESS'), '成功！', $data);
    }

    /**
     * 文件下载
     */
    public function download(Request $request)
    {
        $file_url = $request->input('file');
        $file_url = urldecode($file_url);
        //$file_size = filesize($file); // 失败
        $file = @file_get_contents($file_url);
        if (!$file) {
            header('location:' . getenv("HTTP_REFERER"));
            exit;
        }
        $file_size = strlen($file);
        $file_name = basename($file_url);

        // 方法一 【有的文件打不开？】
        /*$fp = fopen($file_url, 'r');
        // 下载文件需要用到的头
        header('Content-type: application/octet-stream');
        header('Accept-Ranges: bytes');
        header('Accept-Length:' . $file_size);
        header('Content-Disposition: attachment; filename=' . $file_name);
        $buffer = 1024;
        $file_count = 0;
        // 向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);*/

        // 方法二
        ob_end_clean();
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); //强制页面不缓存
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . $file_size);
        header('Content-Disposition: attachment; filename=' . $file_name);
        readfile($file_url);
    }

    /**
     * 获取地区
     */
    public function getRegion(Request $request)
    {
        $param = $request->all();
        $where = [
            ['name', '<>', '市辖区']
        ];
        if (!empty($param['parent_code'])) {
            $where[] = ['parent_code', '=', $param['parent_code']];
        } elseif (isset($param['level']) && strlen($param['level']) > 0) {
            $where[] = ['level', '<', $param['level']];
        } else {
            $where[] = ['level', '<', 3];
        }
        $model = new \App\Models\Region();
        $list = $model->where($where)->select('parent_code', 'area_code', 'name', 'level')->get()->toArray();
        if (!empty($param['parent_code'])) {
            // 动态查询
            $tree = $list;
        } else {
            // 一次性查询完成
            $tree = list_to_tree($list, 'area_code', 'parent_code', 'children', 0);
        }

        return api_response(config('constants.STATUS_SUCCESS'), '', $tree);
    }
}
